package com.ruoyi.lvlian.controller;
import com.ruoyi.common.core.exception.AppException;
import com.ruoyi.common.core.utils.IpAddrUtil;
import com.ruoyi.common.core.utils.OrderNumberGenerator;
import com.ruoyi.common.core.utils.PhoneNumberValidator;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.lvlian.service.ISmsSendService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import io.swagger.annotations.ApiParam;

@Api(value = "公共通用Controller", tags = "公共通用Controller")
@RestController
@RequestMapping("/common")
public class CommonController extends BaseController {


    @Autowired
    private ISmsSendService smsSendService;


    @ApiOperation("获取新增包站时候的id,供给 上传货源的公司  association_id 使用 ,比如供应商就传SELL")
    @GetMapping(value = "/getSnowId")
    public AjaxResult getSnowId(@ApiParam(value = "生成id", required = true)@RequestParam(value ="category" , required = true) String category) {
        return success(  category+IdUtil.createSnowflake(1,1).nextId());
    }



    @ApiOperation("发送短信验证码1")
    @GetMapping("/sendMsg")
    public AjaxResult sendMsg(HttpServletRequest request, String phone)  {
        // 检查手机号
        if (StringUtils.isNotEmpty(phone) && !PhoneNumberValidator.isValidPhoneNumber(phone)) {
            return error("手机号码无效");
        }

        String ip = IpAddrUtil.getIpAddr(request);
        try {
            smsSendService.sendSmsVerificationCode(phone, ip);
        } catch (AppException e) {
            return error( "验证码获取失败"  );
        }
        return success(   );
    }

    @ApiOperation("生成订单号")
    @GetMapping("/generateOrderNumber")
    public AjaxResult generateOrderNumber( )  {
        return success(     OrderNumberGenerator.generateOrderNumber());
    }

    @ApiOperation("生成自然顺序号")
    @GetMapping("/generateSequence")
    public AjaxResult generateSequence(String prefix) {
        // 直接使用 Redis 自增，从1开始
        String sequence = smsSendService.generateSequence( prefix);
        return AjaxResult.success(sequence);
    }


}
